package com.iweipan.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.iweipan.R;
import com.iweipan.activity.ReceiverWebActivity;
import com.iweipan.activity.WPHomeActivity;
import com.tencent.android.tpush.XGPushBaseReceiver;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushRegisterResult;
import com.tencent.android.tpush.XGPushShowedResult;
import com.tencent.android.tpush.XGPushTextMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;


public class MessageReceiver extends XGPushBaseReceiver {
    private Intent intent = new Intent("com.iweipan.receiver.UPDATE_LISTVIEW");
    public static final String LogTag = "TPushReceiver";

    private String content, url, userId, title, actionUrl, actionParam;
    private int urlType, actionType;

    Intent custom_intent;

    private void show(Context context, String text) {
//        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

    // 通知展示
    @Override
    public void onNotifactionShowedResult(Context context,
                                          XGPushShowedResult notifiShowedRlt) {
        if (context == null || notifiShowedRlt == null) {
            Toast.makeText(context, notifiShowedRlt + "", Toast.LENGTH_LONG).show();
            return;
        }
        XGNotification notific = new XGNotification();
        notific.setMsg_id(notifiShowedRlt.getMsgId());
        notific.setTitle(notifiShowedRlt.getTitle());
        notific.setContent(notifiShowedRlt.getContent());
        // notificationActionType==1为Activity，2为url，3为intent
        notific.setNotificationActionType(notifiShowedRlt
                .getNotificationActionType());
        // Activity,url,intent都可以通过getActivity()获得
        notific.setActivity(notifiShowedRlt.getActivity());
        notific.setUpdate_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(Calendar.getInstance().getTime()));
        NotificationService.getInstance(context).save(notific);
        context.sendBroadcast(intent);
        show(context, "您有1条新消息, " + "通知被展示 ， " + notifiShowedRlt.toString());
    }

    @Override
    public void onUnregisterResult(Context context, int errorCode) {
        if (context == null) {
            return;
        }
        String text = "";
        if (errorCode == XGPushBaseReceiver.SUCCESS) {
            text = "反注册成功";
        } else {
            text = "反注册失败" + errorCode;
        }
        Log.d(LogTag, text);
        show(context, text);

    }

    @Override
    public void onSetTagResult(Context context, int errorCode, String tagName) {
        if (context == null) {
            return;
        }
        String text = "";
        if (errorCode == XGPushBaseReceiver.SUCCESS) {
            text = "\"" + tagName + "\"设置成功";
        } else {
            text = "\"" + tagName + "\"设置失败,错误码：" + errorCode;
        }
        Log.d(LogTag, text);
        show(context, text);
    }

    @Override
    public void onDeleteTagResult(Context context, int errorCode, String tagName) {
        if (context == null) {
            return;
        }
        String text = "";
        if (errorCode == XGPushBaseReceiver.SUCCESS) {
            text = "\"" + tagName + "\"删除成功";
        } else {
            text = "\"" + tagName + "\"删除失败,错误码：" + errorCode;
        }
        Log.d(LogTag, text);
        show(context, text);

    }

    // 通知点击回调 actionType=1为该消息被清除，actionType=0为该消息被点击
    @Override
    public void onNotifactionClickedResult(Context context,
                                           XGPushClickedResult message) {
        if (context == null || message == null) {
            return;
        }
        String text = "";
        if (message.getActionType() == XGPushClickedResult.NOTIFACTION_CLICKED_TYPE) {
            // 通知在通知栏被点击啦。。。。。
            // APP自己处理点击的相关动作
            // 这个动作可以在activity的onResume也能监听，请看第3点相关内容
            text = "通知被打开 :" + message;
        } else if (message.getActionType() == XGPushClickedResult.NOTIFACTION_DELETED_TYPE) {
            // 通知被清除啦。。。。
            // APP自己处理通知被清除后的相关动作
            text = "通知被清除 :" + message;
        }
        Toast.makeText(context, "广播接收到通知被点击:" + message.toString(),
                Toast.LENGTH_SHORT).show();
        // 获取自定义key-value
        String customContent = message.getCustomContent();
        if (customContent != null && customContent.length() != 0) {
            try {
                JSONObject obj = new JSONObject(customContent);
                // key1为前台配置的key
                if (!obj.isNull("key")) {
                    String value = obj.getString("key");
                    Log.d(LogTag, "get custom value:" + value);
                }
                // ...
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // APP自主处理的过程。。。


        Log.d(LogTag, text);
        show(context, text);
    }

    @Override
    public void onRegisterResult(Context context, int errorCode,
                                 XGPushRegisterResult message) {
        // TODO Auto-generated method stub
        if (context == null || message == null) {
            return;
        }
        String text = "";
        if (errorCode == XGPushBaseReceiver.SUCCESS) {
            text = message + "注册成功";
            // 在这里拿token
            String token = message.getToken();
        } else {
            text = message + "注册失败，错误码：" + errorCode;
        }
        Log.d(LogTag, text);
        show(context, text);
    }

    // 消息透传
    @Override
    public void onTextMessage(Context context, XGPushTextMessage message) {
        Log.i("XGMessage", message + "");
        // TODO Auto-generated method stub
        String text = "收到消息:" + message.toString();
        // 获取自定义key-value
        String customContent = message.getCustomContent();
        if (customContent != null && customContent.length() != 0) {
            try {
                JSONObject obj = new JSONObject(customContent);
                Log.d(LogTag, customContent);
                // key1为前台配置的key
                if (!obj.isNull("key")) {
                    String value = obj.getString("key");
                    Log.d(LogTag, "get custom value:" + value);
                }
                actionType = obj.getInt("actionType");
                if (actionType == 2) {
                    url = obj.getString("actionUrl");
                    actionUrl = obj.getString("actionUrl");
                    userId = obj.getString("actionTargetId");
                    actionParam = obj.getString("actionParam");
                } else {
                    url = obj.getString("actionUrl");
                    //userId = obj.getString("userId");
                }
                // ...
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // APP自主处理消息的过程...
        Log.d(LogTag, text);
//        Log.d("MessageReceiver", "time:" + time);

        int time = (int) (Math.random()*100000);

        NotificationManager manager = (NotificationManager) context
                .getSystemService(context.NOTIFICATION_SERVICE);
        if (actionType == 1) {
            custom_intent = new Intent(context, ReceiverWebActivity.class);
            custom_intent.putExtra("webUrl", url);
//            Log.i("push_url", url);
            PendingIntent pendingIntent =
                    PendingIntent.getActivity(context, time, custom_intent, PendingIntent.FLAG_ONE_SHOT);
            Notification.Builder builder = new Notification.Builder(context);
            builder.setAutoCancel(true);
            builder.setSmallIcon(R.mipmap.bulldog);
            builder.setTicker("给你发来信息");
            builder.setContentTitle(message.getTitle());
            builder.setContentText(message.getContent());
            builder.setContentIntent(pendingIntent);
            Notification build = builder.build();
            manager.notify(time, build);
        } else if (actionType == 2){
            custom_intent = new Intent(context, WPHomeActivity.class);
//            custom_intent.putExtra("webUrl", url);
            Log.i("push_url", url);
            PendingIntent pendingIntent =
                    PendingIntent.getActivity(context, time, custom_intent, PendingIntent.FLAG_ONE_SHOT);
            Notification.Builder builder = new Notification.Builder(context);
            builder.setAutoCancel(true);
            builder.setSmallIcon(R.mipmap.bulldog);
            builder.setTicker("给你发来信息");
            builder.setContentTitle(message.getTitle());
            builder.setContentText(message.getContent());
            builder.setContentIntent(pendingIntent);
            manager.notify(time, builder.build());
        }



//        else if (actionType == 2) {
//            if (actionUrl.equals("questionList")) {
//
//                Intent cou_intent = new Intent(context, MyQAActivity.class);
//                cou_intent.putExtra("userType", PrefHelper.get().getInt("userType", 0));
//                Log.i("push_userId", userId);
//                PendingIntent pendingIntent_cou =
//                        PendingIntent.getActivity(context, 0, cou_intent, PendingIntent.FLAG_ONE_SHOT);
//                Notification.Builder builder = new Notification.Builder(context);
//                builder.setAutoCancel(true);
//                builder.setSmallIcon(R.mipmap.ic_launcher);
//                builder.setTicker("给你发来信息");
//                builder.setContentTitle(message.getTitle());
//                builder.setContentText(message.getContent());
//                builder.setContentIntent(pendingIntent_cou);
//                manager.notify(0, builder.build());
//                show(context, text);
//            } else if (actionUrl.equals("reservationList")) {
//
//                Intent ord_intent = new Intent(context, OrderActivity.class);
//                ord_intent.putExtra("userType", PrefHelper.get().getInt("userType", 0));
//                Log.i("push_Type", PrefHelper.get().getInt("userType", 0) + "");
//                PendingIntent pendingIntent_ord =
//                        PendingIntent.getActivity(context, 0, ord_intent, PendingIntent.FLAG_ONE_SHOT);
//                Notification.Builder builder = new Notification.Builder(context);
//                builder.setAutoCancel(true);
//                builder.setSmallIcon(R.mipmap.ic_launcher);
//                builder.setTicker("给你发来信息");
//                builder.setContentTitle(message.getTitle());
//                builder.setContentText(message.getContent());
//                builder.setContentIntent(pendingIntent_ord);
//                manager.notify(0, builder.build());
//                show(context, text);
//            } else if (actionUrl.equals("questionInfo")) {
//
//                if (PrefHelper.get().getInt("userType", 0) == 1) {
//
//                    Intent cou_intent = new Intent(context, QuestionInfoActivity.class);
//                    cou_intent.putExtra("id", Integer.parseInt(userId));
//                    //cou_intent.putExtra("counselorId", actionParam);
//                    Log.i("push_userId", userId);
//                    PendingIntent pendingIntent_cou =
//                            PendingIntent.getActivity(context, 0, cou_intent, PendingIntent.FLAG_ONE_SHOT);
//                    Notification.Builder builder = new Notification.Builder(context);
//                    builder.setAutoCancel(true);
//                    builder.setSmallIcon(R.mipmap.beikexl_icon);
//                    builder.setTicker("给你发来信息");
//                    builder.setContentTitle(message.getTitle());
//                    builder.setContentText(message.getContent());
//                    builder.setContentIntent(pendingIntent_cou);
//                    manager.notify(3, builder.build());
//                    show(context, text);
//                } else if (PrefHelper.get().getInt("userType", 0) == 0) {
//
//                    Intent cou_intent = new Intent(context, AnwerInfoActivity.class);
//                    cou_intent.putExtra("id", Integer.parseInt(userId));
//                    cou_intent.putExtra("counselorId", actionParam);
//                    Log.i("push_userId", actionParam);
//                    PendingIntent pendingIntent_cou =
//                            PendingIntent.getActivity(context, 0, cou_intent, PendingIntent.FLAG_ONE_SHOT);
//                    Notification.Builder builder = new Notification.Builder(context);
//                    builder.setAutoCancel(true);
//                    builder.setSmallIcon(R.mipmap.beikexl_icon);
//                    builder.setTicker("给你发来信息");
//                    builder.setContentTitle(message.getTitle());
//                    builder.setContentText(message.getContent());
//                    builder.setContentIntent(pendingIntent_cou);
//                    manager.notify(3, builder.build());
//                    show(context, text);
//                }
//            } else {
//                Intent cou_intent = new Intent(context, HomePageActivity.class);
//                cou_intent.putExtra("userId", userId);
//                Log.i("push_userId", userId);
//                PendingIntent pendingIntent_cou =
//                        PendingIntent.getActivity(context, 0, cou_intent, PendingIntent.FLAG_ONE_SHOT);
//                Notification.Builder builder = new Notification.Builder(context);
//                builder.setAutoCancel(true);
//                builder.setSmallIcon(R.mipmap.beikexl_icon);
//                builder.setTicker("给你发来信息");
//                builder.setContentTitle(message.getTitle());
//                builder.setContentText(message.getContent());
//                builder.setContentIntent(pendingIntent_cou);
//                manager.notify(0, builder.build());
//                show(context, text);
//            }
//        } else if (actionType == 3) {
//            Intent ord_intent = new Intent(context, OrderActivity.class);
//            ord_intent.putExtra("userType", PrefHelper.get().getInt("userType", 0));
//            Log.i("push_Type", PrefHelper.get().getInt("userType", 0) + "");
//            PendingIntent pendingIntent_ord =
//                    PendingIntent.getActivity(context, 0, ord_intent, PendingIntent.FLAG_ONE_SHOT);
//            Notification.Builder builder = new Notification.Builder(context);
//            builder.setAutoCancel(true);
//            builder.setSmallIcon(R.mipmap.beikexl_icon);
//            builder.setTicker("给你发来信息");
//            builder.setContentTitle(message.getTitle());
//            builder.setContentText(message.getContent());
//            builder.setContentIntent(pendingIntent_ord);
//            manager.notify(0, builder.build());
//            show(context, text);
//        }
    }

}
